<script setup>
import {listFavoriteStores, removeFavoriteStore} from "@/api/favorite";
import {getCurrentUserInfo} from "@/api/user";
import {nextTick, onMounted, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {updateFavoriteTagsById} from "@/api/favorite";
import {useRouter} from "vue-router";

const router = useRouter()
const favorites = ref([])
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(10)
const curUserId = ref(0)

// --------初始化获取当前用户ID和收藏列表--------
onMounted(() => {
  getCurUserId().then(() => getFavoriteList())
})
const getCurUserId = () => {
  return getCurrentUserInfo().then(res => {
    curUserId.value = res.data.id
  })
}

// ---------根据用户ID获取收藏列表--------------
const getFavoriteList = () => {
  const query = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    userId: curUserId.value
  }
  listFavoriteStores(query).then(res => {
    favorites.value = res.data.records
    total.value = res.data.total
  })
}

// --------------分页器-----------------
const pageNoChange = (value) => {
  pageNo.value = value
  getFavoriteList()
}
const pageSizeChange = (value) => {
  pageSize.value = value
  getFavoriteList()
}

// --------------收藏标签编辑-----------------
const newTagInput = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref()
const dialogVisible = ref(false)
const selectedFavorite = ref({})
const editFavoriteTags = (row) => {
  dialogVisible.value = true
  selectedFavorite.value = JSON.parse(JSON.stringify(row))
  dynamicTags.value = selectedFavorite.value.tags
}
// 删除一个标签
const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}
// 添加新标签时显示输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value?.input?.focus()
  })
}
const handleInputConfirm = () => {
  if (newTagInput.value) {
    if(dynamicTags.value) {
      dynamicTags.value.push(newTagInput.value)
    } else {
      dynamicTags.value = [newTagInput.value]
    }
  }
  inputVisible.value = false
  newTagInput.value = ''
}
// 保存编辑后的标签
const saveFavoriteTags = () => {
  console.info("id：" + selectedFavorite.value.id)
  console.info(dynamicTags.value)
  const favoriteData = {
    id: selectedFavorite.value.id,
    tags: dynamicTags.value
  }
  updateFavoriteTagsById(favoriteData).then(res => {
    if (res.data) {
      ElMessage.success('标签已更新')
      dialogVisible.value = false
      getFavoriteList()
    } else {
      ElMessage.error('更新标签失败，请稍后再试')
    }
  })
}
// ----------------取消收藏-----------------
const removeFavorite = (row) => {
  console.log("当前点击的店铺的id：", row.store.id)
  ElMessageBox.confirm(
      '是否取消收藏该店铺？',
      '提示',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      }
  ).then(() => {
    const favoriteData = {
      userId: row.userId,
      storeId: row.store.id
    }
    removeFavoriteStore(favoriteData).then(() => {
      ElMessage.warning('已取消收藏')
      getFavoriteList()
    })
  })
}

// ------------前往店铺详情页--------------
const toStorePage = (id) => {
  router.push(`/user/storeDetailsPage/${id}`)
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>我的收藏</span>
      </div>
    </template>
    <div class="content">
      <el-table :data="favorites" style="width: 100%" stripe>
        <el-table-column label="店铺名">
          <template #default="scope">
            <span class="store-name" @click="toStorePage(scope.row.store.id)">{{scope.row.store.name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签">
        <template #default="scope">
          <el-tag
              v-for="tag in scope.row.tags"
              :key="tag"
              type="primary"
              class="tag"
          >{{ tag }}
          </el-tag>
        </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="editFavoriteTags(scope.row)">编辑标签</el-button>
            <el-button type="danger" @click="removeFavorite(scope.row)">取消收藏</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="pageSizeChange"
          @current-change="pageNoChange"
      />

      <!--    编辑弹窗  -->
      <el-dialog v-model="dialogVisible" title="编辑标签" width="500" center>
        <span>
          <el-form label-width="auto" style="max-width: 600px">
            <el-form-item label="我的标签" label-position="top">
              <el-tag
                  v-for="tag in dynamicTags"
                  :key="tag"
                  closable
                  class="tag"
                  :disable-transitions="false"
                  @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                  v-if="inputVisible"
                  ref="InputRef"
                  v-model="newTagInput"
                  class="w-20"
                  size="small"
                  @keyup.enter="handleInputConfirm"
                  @blur="handleInputConfirm"
              />
              <el-button v-else class="button-new-tag" size="small" @click="showInput">
                + 新标签
              </el-button>
            </el-form-item>
          </el-form>
        </span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveFavoriteTags">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </el-card>
</template>

<style scoped lang="scss">
.tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
.store-name {
  cursor: pointer;
}
.store-name:hover {
  color: #409eff;
}
</style>